import semver from "semver";
import * as appService from "../service/app.js";
import * as tipService from "../service/tip.js";
import { rmFieldsFromObject } from "../utils/index.js";

export const opts = {
  cors: {
    origin: "*", // 允许任何来源
    methods: ["GET", "POST"], // 允许的 HTTP 请求类型
  },
};

export const syncClients = async () => {
  const clients = await io.fetchSockets();
  const data = clients.map((item) => ({
    id: item.id,
    room: Array.from(item.rooms)[1],
  }));
  io.in("admin").emit("clientsChange", data);
};

// 从url获取参数
export const getParamsFromUrl = (socket) => {
  const { query } = socket.handshake;
  const fields = ["EIO", "transport", "t"];
  const urlParams = rmFieldsFromObject(query, fields);
  return urlParams;
};



// 低版本升级提示弹窗
export const checkNeedUpdate = async (socket, urlParams) => {
  const app = await appService.getApp(); //获取客户端app最新版本号
  const tooOld = semver.lt(urlParams.version, app.version);
  if (tooOld) {
    const force_update = Boolean(app.force_update);
    socket.emit("modal", {
      force: force_update,
      title: "发现新版本",
      content:app.update_desc,
      okBtnTxt: force_update?'去升级':''
    });
  }
};


// 执行其它弹窗的触发
export const checkOtherModalTask = async (socket, urlParams) => {
  // 获取当前还有没有没有失效的弹窗任务
  const tips = await tipService.getEffectiveTips(urlParams.id);
  for (const element of tips) {
    const force = Boolean(element.force);
    socket.emit("modal", {
      force,
      title: element.title,
      content:element.content
    });
  } 
  // 去除用户已经完成的（给他展示次数已经达标）
};